<?php
namespace app\common\exception;

use think\facade\Config;
use Throwable;

class AdminException extends \Exception
{
    /**
     * @var array 额外传递的数据
     */
    protected $data = [];

    /**
     * AdminException constructor.
     * @param string $message
     * @param int $code
     * @param Throwable|null $previous
     */
    public function __construct($message = "", $code = 0, $data = [], Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
        $this->data = $data;
    }

    /**
     * 输出错误页面
     * @return \think\response\View
     */
    public function render()
    {
        $request = request();
        if ( $request->isAjax() ) {
            return $this->renderWithJson();
        } else {
            return view('./yis/view/admin/error.html', [
                'message' => $this->getMessage()
            ]);
        }
    }

    /**
     * 返回JSON错误信息
     * @return \think\response\Json
     */
    public function renderWithJson()
    {
        if ( (int) config('app.app_debug') === 1)
            $this->data['trace'] = $this->getTrace();
        return json([
            'state' => 'error',
            'code' => $this->getCode(),
            'message' => $this->getMessage(),
            'data' => $this->data
        ]);
    }
}